package com.open.web.listens;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.ServletRequestHandledEvent;


/**
 * @author: codex
 * @Date: 2024/10/19 上午11:53
 * @Version: V1.0
 * @description: | 上面统计了耗时情况，但是不够准确，为了更准确地反应处整个请求处理过程的耗时，包括Spring框架根据请求查找对应的Controller、拦截器执行等操作，SpringMVC在这些过程执行完成后是发布了一个事件，我们可以通过监听该事件来获取整个请求生命周期的耗时，如下示例
 */

@Component
public class TakeTimeContListener implements ApplicationListener<ServletRequestHandledEvent> {

    private static final Logger log = LoggerFactory.getLogger(TakeTimeContListener.class);

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(final ServletRequestHandledEvent event) {
        Throwable failureCause = event.getFailureCause();
        if (failureCause != null) {
            log.error("请求错误，错误原因: {}", failureCause.getMessage());
        }
        log.info("请求客户端地址：{} 请求URL: {}, 请求Method: {}, 请求耗时: {}", event.getClientAddress(), event.getRequestUrl(), event.getMethod(), event.getProcessingTimeMillis());
    }
}
